package com.yuwei.image.picasso

import android.graphics.*
import com.squareup.picasso.Transformation


class PicassoCircleCrop: Transformation{
    override fun transform(source: Bitmap?): Bitmap {
        if (source == null) throw IllegalArgumentException("Source bitmap cannot be null")

        val size = minOf(source.width, source.height)
        val x = (source.width - size) / 2
        val y = (source.height - size) / 2

        val squaredBitmap = Bitmap.createBitmap(source, x, y, size, size)
        if (squaredBitmap != source) {
            source.recycle()
        }

        val output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(output)
        val paint = Paint().apply {
            isAntiAlias = true
            shader = BitmapShader(squaredBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
        }

        canvas.drawCircle(size / 2f, size / 2f, size / 2f, paint)
        squaredBitmap.recycle()
        return output
    }

    override fun key(): String = "circleCrop"


}